package com.bst.bsj.weixin;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.HttpMethodBase;

public class HttpClientUtil {

    private static int    max_bytes = 4096;

    private static String charSet   = "utf-8";

    private static String ENCODING  = "encoding";

    /**
     * 获取返回字符集
     * 
     * @param method
     * @return
     */
    public static String getResponseHeaderCharset(HttpMethodBase method) {

        String vl = method.getResponseHeader("Content-Type").getValue();
        int index = vl.indexOf("encoding");
        String charset = "utf-8";

        if (index > 0) {
            charset = vl.substring(index + ENCODING.length() + 1);
        }

        return charset;
    }

    /**
     * 获取返回内容
     * 
     * @param inputStream
     * @param encode
     * @return
     * @throws IOException
     */
    public static String getResponseBody(InputStream inputStream, String encode) throws IOException {
        byte[] b = new byte[max_bytes];
        StringBuilder builder = new StringBuilder();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int bytesRead = inputStream.read(b, 0, max_bytes);

        while (bytesRead != -1) {
            baos.write(b, 0, bytesRead);
            builder.append(new String(b, 0, bytesRead));
            bytesRead = inputStream.read(b, 0, max_bytes);
        }

        String charEncode = getContentCharset(builder.toString(), encode);
        String content = baos.toString(charEncode);
        baos.close();
        return content;
    }

    private static String getContentCharset(String content, String defaultEncode) {
        String charset = defaultEncode;
        if (matcherCharset(content, "(charset)\\s?=\\s?(utf-?8)")) {
            charset = "utf-8";
        } else if (matcherCharset(content, "(charset)\\s?=\\s?(gbk)")) {
            charset = "gbk";
        } else if (matcherCharset(content, "(charset)\\s?=\\s?(gb2312)")) {
            charset = "gb2312";
        }
        return charset;
    }

    private static boolean matcherCharset(String s, String pattern) {
        Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE + Pattern.UNICODE_CASE);
        Matcher matcher = p.matcher(s);
        if (matcher.find()) {
            return true;
        } else {
            return false;
        }
    }
}
